//
//  TextBox.m
//  AHTest
//
//  Created by ash on 16/8/2.
//  Copyright © 2016年 ash. All rights reserved.
//

#import "TextBox.h"
@interface PHTextView ()
//@property (nonatomic, assign) BOOL showCount;
@end
@implementation PHTextView
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self setup];
    }
    return self;
}

-(instancetype)init{
    if (self = [super init]) {
        [self setup];
    }
    return self;
}

-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        [self setup];
    }
    return self;
}

- (void)setup {
    currentLine = 1;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didReceiveTextDidChangeNotification:)
                                                 name:UITextViewTextDidChangeNotification
                                               object:self];
    
    _placeholderColor = [UIColor lightGrayColor];
    self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    self.scrollIndicatorInsets = UIEdgeInsetsMake(10.0f, 0.0f, 10.0f, 0.0f);
    self.contentInset = UIEdgeInsetsZero;
    self.scrollEnabled = YES;
    self.scrollsToTop = NO;
    self.userInteractionEnabled = YES;
    //self.font = [UIFont systemFontOfSize:16.0f];
    self.textColor = [UIColor blackColor];
    //self.backgroundColor = [UIColor whiteColor];
    self.keyboardAppearance = UIKeyboardAppearanceDefault;
    self.keyboardType = UIKeyboardTypeDefault;
    self.returnKeyType = UIReturnKeyDefault;
    self.textAlignment = NSTextAlignmentLeft;
    self.textContainer.lineBreakMode = NSLineBreakByCharWrapping;
    //self.layoutManager.allowsNonContiguousLayout = NO;//UITextView 中的 layoutManager(NSLayoutManager) 的是否非连续布局属性，默认是 YES，设置为 NO 后 UITextView 就不会再自己重置滑动了
    //self.delegate = self;
}

- (void)didReceiveTextDidChangeNotification:(NSNotification *)notification {
    [self setNeedsDisplay];
    
    NSInteger lines = self.contentSize.height / self.font.lineHeight;
    if (self.maxLines && lines > self.maxLines) {
        return;
    }
    
    if (currentLine != lines && self.changeLineBlock) {
        currentLine = lines;
        self.changeLineBlock(lines);
    }
}

-(NSInteger)textLines{
    return self.contentSize.height / self.font.lineHeight;
}

- (void)dealloc {
    _placeholder = nil;
    _placeholderColor = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:self];
}

#pragma mark - Drawing

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    if (self.placeholderFont==nil) {
        self.placeholderFont=self.font;
    }
    //    if (self.placeholderFont == nil || self.placeholderColor == nil) {
    //        return;
    //    }
    if([self.text length] == 0 && self.placeholder) {
        //占位符的高度
        CGFloat H = [self.placeholder boundingRectWithSize:CGSizeMake(rect.size.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.placeholderFont} context:nil].size.height;
        UIEdgeInsets insets;
        if (!_showCount) {
            //self.textContainerInset = UIEdgeInsetsMake(10, 5, 0, 5);
    
            if (CGRectEqualToRect(self.placeHolderRect, CGRectZero)) {
                if (_isMiddlePlaceholder) {
                    self.textContainerInset = UIEdgeInsetsMake(10, 0, 10, 0);
                    insets = self.textContainerInset;
                    self.placeHolderRect = CGRectMake(0, (rect.size.height - H) / 2.0, rect.size.width, H);
                } else {
                    self.textContainerInset = UIEdgeInsetsMake(10, -5, 0, 0);
                    insets = self.textContainerInset;
                    self.placeHolderRect = CGRectMake(insets.left + 5, 10, rect.size.width, rect.size.height);
                }
            }
        } else {
            insets = self.textContainerInset;
            self.placeHolderRect = CGRectMake(insets.left + 5, insets.top, rect.size.width, rect.size.height);
        }
        [self.placeholderColor set];
        
        if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_0) {
            NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
            paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
            paragraphStyle.alignment = self.textAlignment;
            
            [self.placeholder drawInRect:self.placeHolderRect
                          withAttributes:@{ NSFontAttributeName : self.placeholderFont,NSForegroundColorAttributeName : self.placeholderColor,NSParagraphStyleAttributeName : paragraphStyle }];
        }else {
            [self.placeholder drawInRect:self.placeHolderRect
                                withFont:self.placeholderFont
                           lineBreakMode:NSLineBreakByTruncatingTail
                               alignment:self.textAlignment];
            
        }
    }
}
//-(void)setTextInsets:(UIEdgeInsets)textInsets{
//    //UIEdgeInsets insets = self.scrollIndicatorInsets;
//    self.textContainerInset = UIEdgeInsetsMake(textInsets.top, textInsets.left,textInsets.bottom, textInsets.right);
//}

//- (void)setPlaceHolderTextColor:(UIColor *)placeHolderTextColor {
//}
- (void)setIsMiddlePlaceholder:(BOOL)isMiddlePlaceholder {
    _isMiddlePlaceholder = isMiddlePlaceholder;
    [self setNeedsDisplay];
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor {
    if([placeholderColor isEqual:_placeholderColor]) {
        return;
    }
    _placeholderColor = placeholderColor;
    [self setNeedsDisplay];
}
- (void)setText:(NSString *)text {
    [super setText:text];
    [self setNeedsDisplay];
    /**
     *  这里要注意主动调用一下
     */
    [self didReceiveTextDidChangeNotification:nil];
}

- (void)setAttributedText:(NSAttributedString *)attributedText {
    [super setAttributedText:attributedText];
    [self setNeedsDisplay];
}

- (void)setFont:(UIFont *)font {
    [super setFont:font];
    [self setNeedsDisplay];
}

- (void)setTextAlignment:(NSTextAlignment)textAlignment {
    [super setTextAlignment:textAlignment];
    [self setNeedsDisplay];
}
@end


@interface TextBox()<UITextViewDelegate,UITextFieldDelegate>
@property (nonatomic, assign) BOOL isLimitMode;
@end

@implementation TextBox

//- (instancetype)initWithMaxNumber:(NSInteger)maxNumber
//{
//    if (self = [super init]) {
//
//        [self buildUI];
//    }
//    return self;
//}
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        //默认不受限制
        _isLimitMode = NO;
        _maxNumber = NSIntegerMax;
        [self buildUI];
        [self setupLayout:frame];
    }
    return self;
}
- (instancetype)init
{
    if (self = [super init]) {
        _isLimitMode = NO;
        _maxNumber = NSIntegerMax;
        [self buildUI];
    }
    return self;
}
#pragma ------setter---------
- (void)setTextBoxType:(TextBoxType)textBoxType {
    _textBoxType = textBoxType;
    [self buildUI];
    [self setupLayout:self.frame];
}
- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    [self buildUI];
    [self setupLayout:frame];
}
- (void)setMaxNumber:(NSInteger)maxNumber {
    _maxNumber = maxNumber;
    if (_maxNumber>0) {
        _isLimitMode = YES;
    }else{
        _isLimitMode = NO;
        _maxNumber = NSIntegerMax;
    }
}
- (void)setShowCount:(BOOL)showCount {
    _showCount = showCount;
    [self buildUI];
}
- (void)setIsEditable:(BOOL)isEditable
{
    _isEditable = isEditable;
    if (_textBoxType == TextViewBox) self.textView.editable = _isEditable;
    if (_textBoxType == TextFieldBox) self.textField.enabled = _isEditable;
}

- (void)buildUI
{
    if (_textBoxType == TextViewBox) {
        [self addSubview:self.textView];
        if (_isLimitMode && _showCount) {
            [self addSubview:self.lbLimit];
            self.lbLimit.text = [self limitStringWithNumber:self.textView.text.length];
        }
    }
    if (_textBoxType == TextFieldBox) [self addSubview:self.textField];
}
#pragma ------getter---------
- (UITextView *)textView
{
    if (_textView  == nil) {
        _textView = [[PHTextView alloc] init];
        _textView.showCount = _showCount;
        //_textView.backgroundColor = [UIColor whiteColor];
        //        if (_isLimitMode) {
        //        }
        //_textView.font = [AKUIDesign fontForTextView];
        _textView.delegate = self;
    }
    return _textView;
}
- (UITextField *)textField {
    if (_textField == nil) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeClick:) name:UITextFieldTextDidChangeNotification object:nil];
        _textField = [[UITextField alloc] init];
        _textField.delegate = self;
    }
    return _textField;
}

- (UILabel *)lbLimit
{
    if (_lbLimit == nil) {
        UILabel *lb = [[UILabel alloc] init];
        lb.backgroundColor = [UIColor clearColor];
        lb.font = [UIFont systemFontOfSize:12];
        lb.textColor = [UIColor lightGrayColor];
        //lb.textColor = [AKUIDesign textLightGrayColor];
        lb.textAlignment = NSTextAlignmentRight;
        _lbLimit = lb;
    }
    return _lbLimit;
}
- (void)setupLayout:(CGRect)rect {
    if (_textBoxType == TextViewBox) {
        if (_showCount) {
            self.textView.frame = CGRectMake(0, 0, rect.size.width,  rect.size.height - 19);
            self.lbLimit.frame = CGRectMake(8, rect.size.height - 19, rect.size.width - 16, 14);
        } else {
            self.textView.frame = CGRectMake(0, 0, rect.size.width,  rect.size.height);
        }
    }
    if (_textBoxType == TextFieldBox) self.textField.frame = CGRectMake(0, 0, rect.size.width, rect.size.height);
}
//- (void)setContentString:(NSString *)contentString
//{
//    _contentString = [contentString copy];
//    self.textView.text = contentString;
//    self.lbLimit.text = [self limitStringWithNumber:contentString.length];
//}

//- (NSString *)contentString
//{
//    _contentString = self.textView.text;
//    return _contentString;
//}
-(NSString *)text{
    if (_textBoxType == TextViewBox) return self.textView.text;
    if (_textBoxType == TextFieldBox) return self.textField.text;
    return nil;
}
- (NSString *)limitStringWithNumber:(NSInteger)number
{
    return [NSString stringWithFormat:@"%ld/%ld",(long)number,(long)_maxNumber];
}
#pragma mark ---------TextViewDelegate-------
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    // AKDLog(@"range %@  text %@  lenth %lu",NSStringFromRange(range), text, (unsigned long)textView.text.length);
    if (range.length >= 1) {//删除的情况
        return YES;
    }
    
    if (range.location >= _maxNumber) {
        return NO;
    }
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    _textDidChangeBlock(self);
    NSString *content = textView.text;
    if (content.length>_maxNumber) {
        textView.text = [content substringToIndex:_maxNumber];
    }
    if (_isLimitMode && _showCount) {
        self.lbLimit.text = [self limitStringWithNumber:textView.text.length];
        //[self.lbLimit sizeToFit];
    }
}
#pragma mark ----TextFieldDelegate or Notification------
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    //判断加上输入的字符，是否超过界限
    NSString *str = [NSString stringWithFormat:@"%@%@", textField.text, string];
    if (str.length >= _maxNumber)
    {
        //textField.text = [textField.text substringToIndex:TITLE_WORD_LIMIT];
        return NO;
    }
    return YES;
}
- (void)changeClick:(NSNotification *)notification {
    _textDidChangeBlock(self);
    UITextField *tf = (UITextField *)notification.object;
    //该判断用于联想输入
    if (tf.text.length > _maxNumber)
    {
        tf.text = [tf.text substringToIndex:_maxNumber];
    }
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}
@end

